package top.huxy.web.core;

import cn.hutool.core.io.FileUtil;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import top.huxy.web.util.FileUtils;
import top.huxy.web.util.RequestUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * @author aproz
 * @Date 2022/5/13
 */
public interface ReturnResourceAble {
    default Resource sendBinaryResource(byte[] bytes, String fileName, boolean isDownloadFile) {
        HttpServletResponse currentResponse = RequestUtils.getCurrentResponse();
        currentResponse.setHeader(HttpHeaders.CONTENT_DISPOSITION, isDownloadFile ? "attachment;filename=" + fileName : "inline");
        return new ByteArrayResource(bytes);
    }

    default Resource sendBinaryResource(byte[] bytes, String fileName, boolean isDownloadFile, String contentType) {
        HttpServletResponse currentResponse = RequestUtils.getCurrentResponse();
        currentResponse.setHeader(HttpHeaders.CONTENT_DISPOSITION, isDownloadFile ? "attachment;filename=" + fileName : "inline");
        currentResponse.setContentType(contentType);
        return new ByteArrayResource(bytes);
    }

    default Resource sendBinaryResource(File file, String fileName, boolean isDownloadFile) {
        HttpServletResponse currentResponse = RequestUtils.getCurrentResponse();
        currentResponse.setHeader(HttpHeaders.CONTENT_DISPOSITION, isDownloadFile ? "attachment;filename=" + fileName : "inline");
        currentResponse.setContentType(FileUtils.getContentType(file));
        return new ByteArrayResource(FileUtil.readBytes(file));
    }

    default Resource sendBinaryResource(byte[] bytes) {
        return new ByteArrayResource(bytes);
    }
}
